package com.project;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.project.JDBCProperties.*;
import static com.project.NameUtils.*;
import static com.project.NameUtils.modelNameConvertMappingPath;

/**
 * 获取当前模板所需的数据
 *
 * @author yuan
 * @date 2020/08/02
 */

public class Resources {

    public static Map<String, Object> getData(String tableName) {
        Map<String, Object> data = new HashMap<>();
        data.put("date", DATE);
        data.put("author", AUTHOR);
        String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
        String modelNameLowerCamel = tableNameConvertLowerCamel(tableName);
        String underlineName = getUnderlineName(modelNameUpperCamel);
        data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
        data.put("modelNameUpperCamel", modelNameUpperCamel);
        data.put("modelNameLowerCamel", modelNameLowerCamel);
        data.put("underlineName", underlineName);
        data.put("basePackage", BASE_PACKAGE);
        data.put("remarks", gainTableName(tableName));//表的备注
        data.put("modeListDetails", getTableName(tableName));//表中的字段信息
        return data;
    }

    /**
     * 根据表的名字查询表中的字段值和备注名
     *
     * @param tableName 表的名字
     * @return 字段名称的集合
     */

    public static List<ResultType> getTableName(String tableName) {
        try {
            //1.加载驱动程序
            Class.forName(JDBC_DIVER_CLASS_NAME);
            //2.获得数据库链接
            Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
            //3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT from information_schema.COLUMNS where table_name ='" + tableName + "'"
                    + "and table_schema = '" + DATABASE_NAME + "'");


            //4.处理数据库的返回结果(使用ResultSet类)
            List<ResultType> all = new ArrayList<>();
            while (rs.next()) {
                String column = rs.getString("COLUMN_NAME");
                String name = NameUtils.MapUnderscoreToCamelCase(column);
                String type = rs.getString("DATA_TYPE");
                String remark = rs.getString("COLUMN_COMMENT");
                ResultType resultType = new ResultType(name, type, remark, column);
                all.add(resultType);
            }
            //关闭资源
            rs.close();
            st.close();
            conn.close();
            return all;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据表名获取标备注名
     *
     * @param tableName 表名称
     * @return 表的备注名
     */
    public static String gainTableName(String tableName) {
        try {
            //1.加载驱动程序
            Class.forName(JDBC_DIVER_CLASS_NAME);
            //2.获得数据库链接
            Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
            //3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT table_name ,table_comment FROM information_schema.TABLES WHERE table_schema = '" + DATABASE_NAME + "'   and TABLE_NAME ='" + tableName + "'");
            //4.处理数据库的返回结果(使用ResultSet类)
            StringBuffer sb = new StringBuffer();
            while (rs.next()) {
                String columnName = rs.getString("table_comment");
                sb.append(columnName);
            }
            //关闭资源
            rs.close();
            st.close();
            conn.close();
            return sb.toString();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void generator(String... include) {
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎，默认 Veloctiy
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(PACKAGE_PATH_JAVA);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setKotlin(false); //是否生成 kotlin 代码
        gc.setSwagger2(true);//是否生成Swagger
        gc.setAuthor(AUTHOR);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName(JDBC_DIVER_CLASS_NAME);
        dsc.setUsername(JDBC_USERNAME);
        dsc.setPassword(JDBC_PASSWORD);
        dsc.setUrl(JDBC_URL);
        mpg.setDataSource(dsc);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //控制 不生成 controller  空字符串就行
        templateConfig.setController("");
        templateConfig.setServiceImpl("");
        templateConfig.setService("");
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setInclude(include);
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(BASE_PACKAGE);
        mpg.setPackageInfo(pc);
        // 执行生成
        mpg.execute();
    }
}
